package com.jgsu.farm.controller;

import com.jgsu.farm.entity.*;
import com.jgsu.farm.exception.*;
import com.jgsu.farm.service.EnemyService;
import com.jgsu.farm.utils.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Api(value = "farm/sysuser", tags = "天敌信息管理模块")  //描述信息用的，标注在类上
@RestController
@RequestMapping("farm/sysuser/enemy")
public class EnemyController {
    @Autowired
    EnemyService enemyService;


    @ApiOperation(value = "天敌信息添加功能")
    @PostMapping(value = "/add", produces = "application/json")
    public CommonResult enemyAdd(Enemy enemy) {
        try {
            enemyService.add(enemy);
            log.info("{}天敌添加成功", enemy.getChinesename());
            return CommonResult.success(ResultCode.SUCCESS);
        } catch (DataAddException e) {
            log.info("{}天敌添加失败", enemy.getChinesename());
            throw new DataAddException(e.getCode(), e.getMessage());
        }
    }


    @ApiOperation(value = "天敌信息删除功能")
    @DeleteMapping(value = "/delete", produces = "application/json")
    public CommonResult enemyDelete(@RequestParam("enemyid") Integer enemyid) {
        try {
            enemyService.delete(enemyid);
            log.info("删除id为:{}的天敌信息", enemyid);
            return CommonResult.success(ResultCode.SUCCESS);
        } catch (DataNotExistException e) {
            log.error("不存在id为：{}的天敌信息，删除失败", enemyid);
            throw new DataNotExistException(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation(value = "天敌信息查询功能")
    @GetMapping(produces = "application/json")
    public CommonResult<PageInfo<Enemy>> enemyList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                   @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pagesize) {
        try {
            PageInfo<Enemy> enemyPageInfo = enemyService.findList(page, pagesize);
            log.info("查询第{}页所有植物信息", page);
            return CommonResult.success(enemyPageInfo);
        } catch (DataNotExistException e) {
            log.error("第{}页普植物信息查询失败", page);
            throw new DataNotExistException(e.getCode(), e.getMessage());
        }
    }

    @ApiOperation(value = "天敌信息更新功能")
    @PutMapping(value = "/update", produces = "application/json")
    public CommonResult enemyUpdate(Enemy enemy) {
        try {
            enemyService.update(enemy);
            log.info("天敌信息更新成功，更新id为：{}", enemy.getEnemyid());
            return CommonResult.success(enemy);
        } catch (DataNotExistException e) {
            log.error("更新id = {}的天敌信息失败",enemy.getEnemyid());
            throw new DataNotExistException(e.getCode(), e.getMessage());
        }
    }
}
